package com.xuanrui.commons.exceptions;



import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView businessExceptionHandler(HttpServletRequest req, HttpServletResponse response, Exception ex) throws Exception {

        String code = "";
        String msg = "";


        if (ex != null && ex.getMessage() != null) {
            String[] temp = ex.getMessage().split("@@");
            msg = ex.getMessage();

             log.error("异常：" + ex.getMessage(),ex);

            if (temp != null && temp.length > 1) {
                code = temp[1];
                msg = temp[0];

                log.debug("异常：" + ex.getMessage());

            } else {
                if (!(ex instanceof ExceptionEnum)) {
                    ex.printStackTrace();

                    msg = "系统异常";


                }

            }
        }

        String XmlHttpRequest = req.getHeader("x-requested-with");

        String contentType = req.getContentType();
        System.out.println(contentType);
        String jsonType = req.getHeader("jsonType");
        if (("XMLHttpRequest").equalsIgnoreCase(XmlHttpRequest) || "jsonType".equalsIgnoreCase(jsonType)) {

            try {
                response.setContentType("application/json;charset = UTF-8");

                response.getWriter().print("{\"errorCode\":" + code + ",\"message\":\"" + msg + "\",\"data\":{\"code\":" + code + "},\"success\":false}");


                response.getWriter().flush();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //return null;
            return new ModelAndView();
        }


        ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW);


        // System.out.println( ex.getMessage());
        mav.getModel().put("message", "错误原因:" + ex.getMessage());


        return mav;
    }


}
